<template>
  <div class="container">
    <van-nav-bar title="消息">
      <template #left>
        <div class="navbar-left-text" @click="router.back()">
          <van-icon name="arrow-left" />
          返回
        </div>
      </template>
      <template #right>
        <div class="collect-btn">
          <van-icon name="ellipsis" size="20" />
          <van-icon class="ml15" name="close" size="20" />
        </div>
      </template>
    </van-nav-bar>
    <div class="options">
      <span
        class="affiche"
        :class="active ? 'no-action-title' : 'action-title'"
        @click="changeActive('affiche')"
      >
        <van-badge :dot="afficheDot">活动公告</van-badge>
      </span>

      <span
        class="message"
        :class="active ? 'action-title' : 'no-action-title'"
        @click="changeActive('message')"
      >
        <van-badge :dot="messageDot">订单消息</van-badge>
      </span>
      <div
        class="slider"
        :class="active ? 'messageslider' : 'afficheslider'"
        ref="sliderDOM"
      ></div>
    </div>
    <div class="menage-message">
      <div @click="showDialog" class="menage-left-text">
        <img src="@/assets/delete.png" class="w12 h12" alt="" />
        删除已读
      </div>
      <div class="menage-right-text" @click="readMessage">
        <img src="@/assets/besom.png" class="w12 h12" alt="" />
        一键已读
      </div>
    </div>
    <div class="empty-icon" v-if="!currentRandererList.length">
      <img src="@/assets/empty.png" alt="" />
      <span class="fs16 clo999">暂无消息</span>
    </div>
    <div v-else class="message-card-list-lazy-load" @scroll="scrollLazyLoad">
      <MessageCardList
        :list-data="currentRandererList"
        @onClick="showPopup"
        :awaitText="awaitText"
      />
    </div>

    <DeleteMassage
      :text="toastText"
      :IsShowDialog="IsShowDialog"
      @cancel="cancelDialog"
      @deleteIsReadMessage="deleteIsReadMessage"
    />

    <ProductPopup
      :IsShowPopup="IsShowPopup"
      :popupKey="massageActionKey"
      @delete="showDialog"
      @confirm="readOnceMassage"
    />
    <Getgglodnotifly ref="getgglodnotiflyDOM" />
  </div>
</template>

<script setup lang="ts">
import MessageCardList from './components/message-card-list.vue'
import ProductPopup from './components/product-popup.vue'
import Getgglodnotifly from './components/get-glod-notifly.vue'
import DeleteMassage from './components/delete-message.vue'
import { listData, messageDate } from './init-data'
import { useRouter } from 'vue-router'
import { ref, computed } from 'vue'

const router = useRouter()
const active = ref(0)
const cacheKeyIndex = ref(-1)
const IsShowDialog = ref(false)
const IsShowPopup = ref(false)
const Residuel = ref(true)
const awaitText = ref('没有更多了')
const toastText = ref('是否确认要删除已读通知')
const sliderDOM = ref<HTMLDataElement>()
const massageActionKey = ref<number | null>(null)
const getgglodnotiflyDOM =  ref<InstanceType<typeof Getgglodnotifly> | null>(null) 
const closureFun = requestResiduelList()

const currentRandererList = computed(() =>
  active.value ? messageDate.value : listData.value,
)

const messageDot = computed(() => messageDate.value.some((item) => item.dot))

const afficheDot = computed(() => listData.value.some((item) => item.dot))

function changeActive(type: string) {
  type === 'affiche' ? (active.value = 0) : (active.value = 1)
}

function requestResiduelList() {
  let timer: ReturnType<typeof setTimeout> | null = null
  return () => {
    if (timer) {
      return
    } else {
      awaitText.value = '正在加载'
      timer = setTimeout(() => {
        listData.value.push(
          {
            type: 'notice',
            dot: true,
            title: '免费得iPhone11',
            des: '恭喜获得20个租币，请查收',
            Date: '2020-03-23',
            time: '14:30',
          },
          {
            type: 'notice',
            dot: true,
            title: '这里的字符限制是十二个字',
            des: '恭喜获得20个租币，请查收',
            Date: '2020-03-23',
            time: '14:30',
          },
          {
            type: 'notice',
            dot: true,
            title: '节日赠租币',
            des: '恭喜获得20个租币，请查收',
            Date: '2020-03-23',
            time: '14:30',
          },
        )
        awaitText.value = '没有更多了'
      }, 1000)
    }
    Residuel.value = false
  }
}

function scrollLazyLoad(event: Event) {
  const { scrollTop, clientHeight, scrollHeight } = event.target as HTMLElement
  if (clientHeight + scrollTop >= scrollHeight - 10 && Residuel) {
    // 模拟请求加入到列表中
    closureFun()
  }
}

// 操作数据后更新视图
function readMessage(): void {
  if (!active.value && listData.value.length) {
    // 对公告栏的所有信息已读处理
    listData.value.forEach((_item, index, arr) => {
      arr[index].dot = false
    })
  } else if (active.value && messageDate.value.length) {
    // 对消息栏的信息已读处理
    messageDate.value.forEach((_item, index, arr) => {
      arr[index].dot = false
    })
  }
}

// 打开消息详情弹出层
function showPopup(keyindex: number) {
  massageActionKey.value = keyindex
  IsShowPopup.value = true
}

// 关闭消息详情弹出层
function closePopup() {
  IsShowPopup.value = false
}

// 打开删除确认框
function showDialog(...args: []) {
  if (!currentRandererList.value.length) return
  closePopup()
  const keyIndexArr = Array.from(args)
  if (keyIndexArr.length && typeof keyIndexArr[0] === 'number') {
    toastText.value = '是否确定要删除此条通知'
    cacheKeyIndex.value = keyIndexArr[0]
  } else {
    toastText.value = '是否确认要删除已读通知'
  }
  IsShowDialog.value = true
}

// 关闭消息确认框
function cancelDialog() {
  IsShowDialog.value = false
}

// 删除其中某个消息
function deleteOnceMassage(keyIndex: number) {
  if (!active.value && listData.value.length) {
    // 对公告栏的所有信息删除处理
    listData.value = listData.value.filter((_i, index) => index !== keyIndex)
  } else if (active.value && messageDate.value.length) {
    // 对消息栏的信息删除处理
    messageDate.value = messageDate.value.filter(
      (_i, index) => index !== keyIndex,
    )
  }
  cacheKeyIndex.value = -1
  closePopup()
}

// 阅读其中某个消息
function readOnceMassage(keyIndex: number) {
  if (!currentRandererList.value[keyIndex].dot) {
    closePopup()
    return
  }
  if (!active.value && listData.value.length) {
    listData.value[keyIndex].dot = false
  } else if (active.value && messageDate.value.length) {
    messageDate.value[keyIndex].dot = false
  }
  closePopup()
  getgglodnotiflyDOM.value?.useClosure(
    currentRandererList.value[keyIndex],
  )
}

// 删除阅读过的消息||删除某条消息
function deleteIsReadMessage() {
  if (cacheKeyIndex.value >= 0) {
    deleteOnceMassage(cacheKeyIndex.value)
    cancelDialog()
    return
  }

  if (!active.value && listData.value.length) {
    listData.value = listData.value.filter((item) => item.dot)
  } else if (active.value && messageDate.value.length) {
    messageDate.value = messageDate.value.filter((item) => item.dot)
  }
  cancelDialog()
}
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.message-card-list-lazy-load {
  flex: 1;
  overflow-y: scroll;
}
.menage-right-text {
  font-size: 12px;
  color: #999;
  display: flex;
  justify-content: start;
  align-items: center;
  border-left: #d9d9d9 solid 1px;
  margin: 15px 15px 15px 0;
  padding-left: 15px;
}
.menage-left-text {
  font-size: 12px;
  color: #999;
  display: flex;
  justify-content: start;
  align-items: center;
  padding: 15px;
}
.empty-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin-top: 50px;

  img {
    height: 160px;
    width: 160px;
  }
}

.menage-message {
  display: flex;
  justify-content: left;
  align-items: center;
  background: #f7f8f9;
  height: 42px;
}

.navbar-left-text {
  font-size: 18px;
  color: var(--van-nav-bar-icon-color);
}

.collect-btn {
  margin-left: 5px;
  padding: 3px 12px;
  border-radius: 50px;
  border: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--van-nav-bar-icon-color);
}

.no-action-title {
  line-height: 16px;
  font-size: 16px;
  color: #666;
}

.affiche {
  display: inline-block;
  padding-left: 15px;
  padding-top: 15px;
}

.message {
  display: inline-block;
  padding-left: 25px;
  padding-top: 15px;
}

.action-title {
  line-height: 20px;
  font-size: 20px;
  color: #333;
  font-weight: bold;
}

@keyframes slider {
  0% {
    transform: translateX(0);
  }

  100% {
    transform: translateX(88px);
  }
}

@keyframes backslider {
  0% {
    transform: translateX(88px);
  }

  100% {
    transform: translateX(0);
  }
}

.options {
  position: relative;
  margin-bottom: 23px;

  .slider {
    width: 20px;
    height: 4px;
    background: #00c8be;
    border-radius: 2.5px;
    position: absolute;
    bottom: -9px;
    left: 45px;
    transform: translateX(0);
  }

  .messageslider {
    transform: translateX(88px);
    animation-name: slider;
    animation-timing-function: ease-in-out;
    animation-iteration-count: 1;
    animation-duration: 0.5s;
    animation-fill-mode: forwards;
  }

  .afficheslider {
    transform: translateX(0px);
    animation-name: backslider;
    animation-timing-function: ease-in-out;
    animation-iteration-count: 1;
    animation-duration: 0.5s;
    animation-fill-mode: forwards;
  }
}
</style>
